package com.stockz.downloader.span;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Collections;
import java.util.Date;
import java.util.List;

import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import com.stockz.downloader.breadth.bse.BseBarSpanCSVParser;
import com.stockz.equity.model.Bar;

@Component
public class BseDailyBarSpanDownloader {

	private String url = "http://charting.bseindia.com/charting/history.asp";
	private String symbolLookupUrl_1 = "http://bseindia.com/bseplus/Common/backpageAsset.aspx?inputstr=";
	private String symbolLookupUrl_2 = "&strFlag=0&ShowSusp=true&no=";
	private String symbolTxt = "SYMBOL";
	private String periodTxt = "period";
	private String endDateTxt = "ENDDATE";
	private String startDateTxt = "STARTDATE";
	private String period = "days";
	
	private Date startDate;
	private Date endDate;
	private String scripCode;
	
	@SuppressWarnings({ "deprecation", "unchecked" })
	public List<Bar> download(){
		
		if(startDate == null){
			throw new NullPointerException("Start date for download is null");
		}
		if(endDate == null){
			throw new NullPointerException("End date for download is null");
		}
		if(StringUtils.hasText(scripCode)){
			throw new NullPointerException("Scrip code for download is null");
		}
		try {
			DataInputStream is = new DataInputStream(
					new BufferedInputStream(
							new URL(constructUrl(getSymbol(),startDate,endDate)).openStream()));
			StringBuffer sb = new StringBuffer();
			String s;
			while((s = is.readLine())!=null){
				sb.append("\n"+s);
			}
			
			return BseBarSpanCSVParser.parseCsv(sb.toString());
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return Collections.EMPTY_LIST;
	}
	
	
	
	private String getSymbol(){
		String symbol = null;
		try {
			String s = new BufferedReader(new InputStreamReader(
							new URL(symbolLookupUrl_1+scripCode+symbolLookupUrl_2+Math.random()).openStream())).readLine();
			if(s!=null)
				symbol = s.substring(0, s.indexOf(":"));
			else
				System.out.println("Symbol not found for : "+scripCode);
		}catch(Throwable t){
			t.printStackTrace();
		}
		return symbol;
	}
	
	private String constructUrl(String symbol,Date startDate, Date endDate){
		return url+"?"
			+symbolTxt+"="+constructSymbol(symbol)
			+"&"+periodTxt+"="+period
			+"&"+endDateTxt+"="+constructDate(endDate)
			+"&"+startDateTxt+"="+constructDate(startDate);
	}
	
	@SuppressWarnings("deprecation")
	private String constructSymbol(String str){
		return URLEncoder.encode(str);
	}
	
	@SuppressWarnings("deprecation")
	private String constructDate(Date date){
		return (date.getMonth() + 1) + "-" + date.getDate() + "-" + (1900 + date.getYear());
	}



	public Date getStartDate() {
		return startDate;
	}



	public void setStartDate(Date startDate) {
		this.startDate = startDate;
	}



	public Date getEndDate() {
		return endDate;
	}



	public void setEndDate(Date endDate) {
		this.endDate = endDate;
	}



	public String getScripCode() {
		return scripCode;
	}



	public void setScripCode(String scripCode) {
		this.scripCode = scripCode;
	}
	
}
